import axios from 'axios';
import React, { useEffect, useState } from 'react';
import { Button, Table, message as antdMessage, Modal, Form, Input, Space, } from 'antd'
const Index = () => {
  const [list, setList] = useState([])
  const [name, setName] = useState('')

  const [flag, setFlag] = useState(true)
  const getList = async () => {
    const resp = await axios.get('/api/list', { params: { name } });
    console.log(resp.data.data);
    setList(resp.data.data)
  }

  const columns = [{
    title: 'id',
    dataIndex: 'id',
    key: 'id'
  }, {
    title: 'name',
    dataIndex: 'name',
    key: 'name'
  }, {
    title: 'word',
    dataIndex: 'word',
    key: 'word'
  }, {
    title: 'image',
    dataIndex: 'image',
    key: 'image',
    render(image) {
      return <img src={image} alt="" height={50} width={50} />
    }
  }, {
    title: '操作',
    render(row) {
      return (
        <Space>
          <Button type="primary" danger onClick={() => handleEdit(row)}>编辑</Button>
          <Button type="primary" danger onClick={() => handleDelete(row.id)}>删除</Button>
        </Space>
      )
    }
  }]

  const handleEdit = (row) => {
    setOpen(true);
    setFlag(false)
    form.setFieldsValue(row)
  }

  const handleDelete = async (id) => {
    await axios.delete('/api/list', { params: { id } });
    await getList();
    antdMessage.success('删除成功')
  }

  const [open, setOpen] = useState(false);

  const [form] = Form.useForm()

  const handleOk = async () => {
    setOpen(false);
    const data = form.getFieldsValue()
    if (flag) {
      await axios.post('/api/list', data);
    } else {
      await axios.post('/api/list/edit', data);
    }
    antdMessage.success('操作成功')
    getList()
  }
  const handleSeasrch = (value) => {
    setName(value)
  }

  useEffect(() => {
    getList()
  }, [name])

  return (
    <div>
      <Input.Search onSearch={value => handleSeasrch(value)}></Input.Search>

      <Button type="primary" onClick={() => { setFlag(true); setOpen(true) }}>添加</Button>

      <Table dataSource={list} columns={columns}></Table>

      <Modal
        onOk={() => handleOk()}
        onCancel={() => setOpen(false)}
        open={open}
        title="添加"
        okText="确定"
        cancelText="取消"
      >
        <Form form={form}>
          <Form.Item label="id" name="id">
            <Input placeholder='请输入id' disabled></Input>
          </Form.Item>
          <Form.Item label="姓名" name="name">
            <Input placeholder='请输入姓名'></Input>
          </Form.Item>
          <Form.Item label="描述" name="word">
            <Input placeholder='请输入描述'></Input>
          </Form.Item>
          <Form.Item label="图片" name="image">
            <Input placeholder='请输入图片'></Input>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  )
}

export default Index